// pages/test-details/test-details.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    result: [],
    pageSize: 20,
    list: [],
    index: 0,
    answersObj: {},
    show: false,
    time: '20:00',
    isPlain: true,
    proVal: 100,
    testTime: 0,
    timeOver: false,
    gradientColor: {
      '0%': '#e35f87',
      '100%': '#61c3e8',
    },
    isLast: false
  },

  // 点击选项
  tabClick(e) {
    let index = e.target.dataset.index
    this.setData({
      index: index,
      show: false,
      result: this.data.answersObj[index] ? this.data.answersObj[index].split('') : []
    })
  },

  // 交卷
  doPaper() {
    this.doChangeQuestion()
    Dialog.confirm({
        message: '真的考虑好要交卷了吗？',
      })
      .then(() => {
        this.setData({
          timeOver: true,
          isLast: true
        })
        let time = this.data.testTime,
          min = Math.floor(time / 60),
          sec = time % 60
        Dialog.alert({
          title: '恭喜完成答卷~',
          message: `成绩：${this.getScore()}分\n用时：${this.fillZero(min)+":"+this.fillZero(sec)}`,
        }).then(() => {
          wx.switchTab({
            url: '../test/test',
          })
        });
      })
      .catch(() => {
        // on cancel
      });
  },

  // 获取考试用时
  getTestTime(cb) {
    let timer = setInterval(() => {
      if (this.data.timeOver) {
        clearInterval(timer)
      }
      this.setData({
        testTime: this.data.testTime + 1
      })
    }, 1000)
  },

  // 算分数
  getScore() {
    let num = 100 / this.data.pageSize
    let score = this.data.list.reduce((i, v) => {
      if (v.type == "success") {
        return i += num
      } else {
        return i
      }
    }, 0)
    return score
  },

  // 处理倒计时
  getTime() {
    let time = this.data.time.split(":")[0],
      totalTime = time * 60,
      // totalTime = time,
      currentTime = totalTime
    let timer = setInterval(() => {
      currentTime--
      if (currentTime <= 0) {
        clearInterval(timer)
        Dialog.alert({
          title: '时间到！',
          message: `成绩：${this.getScore()}分\n用时：20分钟`,
        }).then(() => {
          wx.switchTab({
            url: '../test/test',
          })
        });
      } else if (this.data.timeOver) {
        clearInterval(timer)
      }
      let min = Math.floor(currentTime / 60),
        sec = currentTime % 60
      this.setData({
        time: this.fillZero(min) + ":" + this.fillZero(sec),
        proVal: Math.round((currentTime / totalTime) * 100)
      })
    }, 1000)
  },

  // 补零
  fillZero(num) {
    return num < 10 ? '0' + num : num
  },

  // 获取随机试题数据
  getList() {
    wx.request({
      url: 'http://172.20.10.5:2345/exam/rand-list',
      data: {
        pageSize: this.data.pageSize
      },
      success: res => {
        this.setData({
          list: this.dealList(res.data.data)
        })
      }
    })
  },

  // 处理List数组 - 转为JSON对象
  dealList(arr) {
    return (arr.map(item => {
      return {
        ...item,
        answers: JSON.parse(item.answers),
        options: JSON.parse(item.options),
        type: 'primary'
      }
    }))
  },

  // 显示弹出层
  showPopup() {
    this.setData({
      show: true
    });
  },

  // 隐藏弹出层
  onClose() {
    this.setData({
      show: false
    });
  },

  // 点击上/下一题 
  doChangeQuestion(e) {
    let aors = e && e.target.dataset.aors,
      newObj = this.data.answersObj,
      index = this.data.index,
      currentIndex = aors ? this.data.index + 1 : this.data.index - 1,
      list = this.data.list,
      isLast = this.data.isLast
    newObj[index] = this.data.result.sort().join('')
    if (!newObj[index]) {
      list[index].type = 'primary'
    } else {
      if (newObj[index] == list[index].answers.sort().join("")) {
        list[index].type = "success"
      } else {
        list[index].type = "danger"
      }
    }
    this.setData({
      list: list,
      index: isLast ? index : currentIndex,
      result: isLast ? newObj[index].split("") : newObj[currentIndex] ? newObj[currentIndex].split("") : [],
      answersObj: newObj
    })
  },

  // 选择答案
  onChange(event) {
    this.setData({
      result: event.detail,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let {
      mode
    } = options
    this.getList()
    this.getTime()
    this.getTestTime()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})